package 并发编程07.ForkJoin框架读取文本内容;

import com.sun.javafx.collections.MappingChange;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.RecursiveTask;

/**
 * 作者：idea
 * 日期：2018/8/19
 * 描述：
 */
public class FileRecursiveTask extends RecursiveTask<Map<String,Integer>> {

    private List<String> contents;

    public FileRecursiveTask(File file) {
        System.out.println("处理文件：" + file.getAbsolutePath());
        try {
            contents = Files.readAllLines(Paths.get(file.toURI()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected Map<String, Integer> compute() {
        Map<String,Integer> map=new HashMap<>();
        for(String content:contents){
            String[] strs=content.split(" ");
            for (String str : strs) {
                if(map.containsKey(str)){
                    int val=map.get(str);
                    map.put(str,val++);
                }else {
                    map.put(str,1);
                }
            }
        }
        return map;
    }
}
